<?php
require_once('./includes/headers.inc.php');
require_once('./top.php');

$error = FALSE;
if(isset($_SESSION['msg']) && $_SESSION['msg']) {
    $error = $_SESSION['msg'];
    unset($_SESSION['msg']);
}
$routes = $userMgr->getUserFeed($_SESSION['user']['id'], 30);
if(!$routes) {
    $error = $msgMgr->get('register-success');
}

$lastRoutes = array('<ul id="feed">');
$lastDate = '';
$lastUserId = 0;
$lastLocationId = 0;
$lang = array(
    'short' => $langMgr->get('text_short'),
    'completed' => $langMgr->get('text_completed'),
);
foreach($routes as $row) {
    switch($row['completed']) {
        case -1:
            $completed = '<span class="notcompleted" title="' . $langMgr->get('text_notcompleted') . '">&nbsp;</span>';
            break;
        case 0:
            $completed = '<span class="completed" title="' . $langMgr->get('text_completed') . '">&nbsp;</span>';
            break;
        default:
            $text = $langMgr->get('text_completed_with_x_blocks', FALSE, array('num' => $row['completed']));
            $completed = '<span class="blockcompleted" title="' . $text . '">&nbsp;</span>';
            break;
    }
    $own = ($row['user_id'] == $_SESSION['user']['id'] ? TRUE : FALSE);
    $date = date('d-m-Y', strtotime($row['timestamp']));
    if($date != $lastDate || $row['user_id'] != $lastUserId || $row['location_id'] != $lastLocationId) {
        $firstItem = TRUE;
        $header = '<li class="user ' . ($own ? 'own' : '') . '"><a href="/viewuser.php?id=' . $row['user_id'] . '">' . $row['name'] . '</a>' .
            '<span class="date">' . $date . '<span></li>';
    } else {
        $firstItem = FALSE;
        $header = '';
    }
    $item = array(
        $header,
        '<li class="location ' . ($own ? 'own' : '') . '">' . ($firstItem ? '<a href="/viewlocation.php?id=' . $row['location_id'] . '">' . $row['location'] . '</a>' : ''),
        '<ul>',
            '<li class="route">' . $completed . '<span class="colour ' . $row['colour'] . '"><a href="/viewroute.php?id=' . $row['route_id'] . '">' . $langMgr->get($row['colour_lang']) . ' ' . $row['difficulty'] . ($row['is_short'] ? ' (' . $lang['short'] . ')' : '') . '</a></span> ' . ($row['unicode'] ? '<img class="routetype ' . $row['route_type'] . '" src="/img/pixel.png"> ' : '') . '<i>' . $row['route_name'] . '</i></li>',
            ($row['comment'] ? '<li class="comment">' . $row['comment'] . '</li>' : ''),
            '</ul></li>'
    );
    $lastRoutes[] = implode("\n", $item);
    $lastDate = $date;
    $lastUserId = $row['user_id'];
    $lastLocationId = $row['location_id'];
}
$lastRoutes[] = '</ul>';

$replaces = array(
    'feed'      => implode("\n", $lastRoutes),
    'error'     => $msgMgr->formatMsg($error),
);
$templateMgr->loadContent('feed', array_merge($replaces, $lang));
?>
